using DesktopWidgetApp.Shared;
using DesktopWidgetApp.Core.Data;
using DesktopWidgetApp.Core.Helpers;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.IO;

namespace DesktopWidgetApp.UI.Helpers
{
    /// <summary>
    /// 状态同步辅助类
    /// 负责处理本地状态与服务器状态的同步
    /// </summary>
    public class StatusSyncHelper
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "https://localhost:5001/api"; // 与服务器Program.cs中配置的一致
        private const int MaxRetryAttempts = 3;
        private const int RetryDelayMs = 1000;
        private readonly string _pendingChangesFilePath;

        public StatusSyncHelper()
        {
            _httpClient = new HttpClient
            {
                Timeout = TimeSpan.FromSeconds(10)
            };
            
            // 设置待同步更改文件路径
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            var appFolder = Path.Combine(appDataPath, "DesktopWidgetApp");
            if (!Directory.Exists(appFolder))
            {
                Directory.CreateDirectory(appFolder);
            }
            _pendingChangesFilePath = Path.Combine(appFolder, "pending_changes.json");
        }

        /// <summary>
        /// 将本地状态同步到服务器
        /// </summary>
        /// <param name="status">要同步的状态</param>
        /// <returns>同步是否成功</returns>
        public async Task<bool> SyncStatusToServerAsync(Status status)
        {
            if (status == null)
                return false;

            try
            {
                var jsonContent = JsonSerializer.Serialize(status);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                // 重试逻辑
                for (int attempt = 1; attempt <= MaxRetryAttempts; attempt++)
                {
                    try
                    {
                        var response = await _httpClient.PostAsync($"{_apiBaseUrl}/Status", content); // 使用服务器端定义的端点
                        if (response.IsSuccessStatusCode)
                        {
                            // 同步成功，清除待同步队列中的此状态
                            await RemovePendingChangeAsync(status.Id);
                            return true;
                        }
                        
                        // 如果不是网络错误，不重试
                        if (!response.StatusCode.ToString().StartsWith("5") && response.StatusCode != System.Net.HttpStatusCode.RequestTimeout)
                        {
                            break;
                        }
                    }
                    catch (HttpRequestException)
                    {
                        // 网络错误，继续重试
                    }
                    
                    // 最后一次尝试失败，不再重试
                    if (attempt == MaxRetryAttempts)
                        break;
                    
                    // 等待一段时间后重试
                    await Task.Delay(RetryDelayMs * attempt);
                }
                
                // 所有重试都失败，保存到待同步队列
                await SavePendingChangeAsync(status);
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine("同步状态到服务器失败: " + ex.Message);
                // 保存到待同步队列
                try
                {
                    await SavePendingChangeAsync(status);
                }
                catch (Exception saveEx)
                {
                    Console.WriteLine("保存待同步状态失败: " + saveEx.Message);
                }
                return false;
            }
        }

        /// <summary>
        /// 从服务器获取最新状态
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>从服务器获取的最新状态，如果获取失败则返回null</returns>
        public async Task<Status> GetLatestStatusFromServerAsync(Guid userId)
        {
            try
            {
                // 重试逻辑
                for (int attempt = 1; attempt <= MaxRetryAttempts; attempt++)
                {
                    try
                    {
                        var response = await _httpClient.GetAsync($"{_apiBaseUrl}/Status/{userId}"); // 使用服务器端定义的端点
                        if (response.IsSuccessStatusCode)
                        {
                            var jsonString = await response.Content.ReadAsStringAsync();
                            return JsonSerializer.Deserialize<Status>(jsonString);
                        }
                        
                        // 如果不是网络错误，不重试
                        if (!response.StatusCode.ToString().StartsWith("5") && response.StatusCode != System.Net.HttpStatusCode.RequestTimeout)
                        {
                            break;
                        }
                    }
                    catch (HttpRequestException)
                    {
                        // 网络错误，继续重试
                    }
                    
                    // 最后一次尝试失败，不再重试
                    if (attempt == MaxRetryAttempts)
                        break;
                    
                    // 等待一段时间后重试
                    await Task.Delay(RetryDelayMs * attempt);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("从服务器获取最新状态失败: " + ex.Message);
            }
            
            return null;
        }

        /// <summary>
        /// 获取指定用户是否处于免打扰状态
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户是否处于免打扰状态</returns>
        public async Task<bool> IsUserInDoNotDisturbAsync(Guid userId)
        {
            try
            {
                // 先尝试从服务器获取
                // 服务器端暂未实现免打扰状态端点，注释掉该功能
            // var response = await _httpClient.GetAsync($"{_apiBaseUrl}/Status/{userId}/dnd");
            // if (response.IsSuccessStatusCode)
            // {
            //     var jsonString = await response.Content.ReadAsStringAsync();
            //     return JsonSerializer.Deserialize<bool>(jsonString);
            // }
                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();
                    return JsonSerializer.Deserialize<bool>(jsonString);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取免打扰状态失败: " + ex.Message);
            }
            
            // 默认返回false，表示无法确定用户是否处于免打扰状态
            return false;
        }

        /// <summary>
        /// 测试服务器连接是否正常
        /// </summary>
        /// <returns>服务器连接是否正常</returns>
        public async Task<bool> TestServerConnectionAsync()
        {
            try
            {
                var response = await _httpClient.GetAsync($"{_apiBaseUrl}/Test/ping");
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }
        
        /// <summary>
        /// 同步所有待处理的更改
        /// </summary>
        /// <returns>成功同步的状态数量</returns>
        public async Task<int> SyncPendingChangesAsync()
        {
            if (!await TestServerConnectionAsync())
            {
                return 0; // 服务器不可用
            }
            
            int successfulSyncs = 0;
            
            try
            {
                var pendingChanges = await LoadPendingChangesAsync();
                
                foreach (var status in pendingChanges)
                {
                    if (await SyncStatusToServerAsync(status))
                    {
                        successfulSyncs++;
                    }
                }
                
                // 如果所有待同步更改都已处理，清空文件
                if (successfulSyncs == pendingChanges.Count)
                {
                    await ClearPendingChangesAsync();
                }
                else
                {
                    // 否则只保存未成功同步的更改
                    var remainingChanges = await LoadPendingChangesAsync();
                    await SavePendingChangesAsync(remainingChanges);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("同步待处理更改失败: " + ex.Message);
            }
            
            return successfulSyncs;
        }
        
        /// <summary>
        /// 执行完整同步（双向同步并解决冲突）
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="localRepository">本地状态仓库</param>
        /// <returns>同步是否成功</returns>
        public async Task<bool> PerformFullSyncAsync(Guid userId, IStatusRepository localRepository)
        {
            try
            {
                // 1. 测试服务器连接
                if (!await TestServerConnectionAsync())
                {
                    // 服务器不可用，使用本地数据
                    return false;
                }
                
                // 2. 先同步待处理的更改
                await SyncPendingChangesAsync();
                
                // 3. 从服务器获取最新状态
                var serverStatus = await GetLatestStatusFromServerAsync(userId);
                
                if (serverStatus != null)
                {
                    // 4. 获取本地当前状态
                    var localStatus = await localRepository.GetCurrentStatusByUserIdAsync(userId);
                    
                    // 5. 解决冲突并更新本地数据
                    if (localStatus != null)
                    {
                        // 比较最后更新时间
                        if (serverStatus.LastUpdated > localStatus.LastUpdated)
                        {
                            // 服务器状态更新，更新本地
                            await localRepository.EndCurrentStatusAsync(userId, DateTime.Now);
                            await localRepository.AddAsync(serverStatus);
                        }
                        else if (serverStatus.LastUpdated < localStatus.LastUpdated)
                        {
                            // 本地状态更新，更新服务器
                            await SyncStatusToServerAsync(localStatus);
                        }
                        // 如果时间相同，无需操作
                    }
                    else
                    {
                        // 本地没有状态，使用服务器状态
                        await localRepository.AddAsync(serverStatus);
                    }
                }
                
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("执行完整同步失败: " + ex.Message);
                return false;
            }
        }
        
        #region 私有辅助方法
        
        /// <summary>
        /// 保存待同步的状态更改
        /// </summary>
        private async Task SavePendingChangeAsync(Status status)
        {
            try
            {
                var pendingChanges = await LoadPendingChangesAsync();
                
                // 移除已存在的相同ID的状态
                pendingChanges.RemoveAll(s => s.Id == status.Id);
                
                // 添加新状态
                pendingChanges.Add(status);
                
                await SavePendingChangesAsync(pendingChanges);
            }
            catch (Exception ex)
            {
                Console.WriteLine("保存待同步状态失败: " + ex.Message);
                throw;
            }
        }
        
        /// <summary>
        /// 从待同步队列中移除指定的状态
        /// </summary>
        private async Task RemovePendingChangeAsync(Guid statusId)
        {
            try
            {
                var pendingChanges = await LoadPendingChangesAsync();
                pendingChanges.RemoveAll(s => s.Id == statusId);
                await SavePendingChangesAsync(pendingChanges);
            }
            catch (Exception ex)
            {
                Console.WriteLine("从待同步队列移除状态失败: " + ex.Message);
            }
        }
        
        /// <summary>
        /// 加载所有待同步的状态更改
        /// </summary>
        private async Task<List<Status>> LoadPendingChangesAsync()
        {
            try
            {
                if (!File.Exists(_pendingChangesFilePath))
                {
                    return new List<Status>();
                }
                
                var jsonString = await File.ReadAllTextAsync(_pendingChangesFilePath);
                return JsonSerializer.Deserialize<List<Status>>(jsonString) ?? new List<Status>();
            }
            catch (Exception ex)
            {
                Console.WriteLine("加载待同步状态失败: " + ex.Message);
                return new List<Status>();
            }
        }
        
        /// <summary>
        /// 保存所有待同步的状态更改
        /// </summary>
        private async Task SavePendingChangesAsync(List<Status> pendingChanges)
        {
            try
            {
                var jsonString = JsonSerializer.Serialize(pendingChanges);
                await File.WriteAllTextAsync(_pendingChangesFilePath, jsonString);
            }
            catch (Exception ex)
            {
                Console.WriteLine("保存待同步状态列表失败: " + ex.Message);
                throw;
            }
        }
        
        /// <summary>
        /// 清空所有待同步的状态更改
        /// </summary>
        private async Task ClearPendingChangesAsync()
        {
            try
            {
                if (File.Exists(_pendingChangesFilePath))
                {
                    File.Delete(_pendingChangesFilePath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("清空待同步状态失败: " + ex.Message);
            }
        }
        
        #endregion
    }
}